package com.itao.spel;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;

/**
 * @author sjt
 * @Date 2024/9/30 10:01
 */
public class QuickStart {

    public static void main(String[] args) {
        m2();
    }

    /**
     * 简单表达式计算
     */
    public static void m1() {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Hello World'");
        String message = (String) exp.getValue();
        System.out.println(message); // Hello World
    }

    /**
     * 带模板的表达式计算(#{exp})
     */
    public static void m2() {
        ExpressionParser parser = new SpelExpressionParser();
        // 解析#{}
        ParserContext parserContext = ParserContext.TEMPLATE_EXPRESSION;
        Expression exp1 = parser.parseExpression("'Hello World'", parserContext);
        Expression exp2= parser.parseExpression("${'Hello World'}", TEMPLATE_$EXPRESSION);
        Expression exp3= parser.parseExpression("#{'Hello World'}", parserContext);
        String message1 = (String) exp1.getValue();
        String message2 = (String) exp2.getValue();
        String message3 = (String) exp3.getValue();
        System.out.println(message1); // 'Hello World'
        System.out.println(message2); // Hello World
        System.out.println(message3); // Hello World
    }

    // 解析${}
    static ParserContext TEMPLATE_$EXPRESSION = new ParserContext() {

        @Override
        public boolean isTemplate() {
            return true;
        }

        @Override
        public String getExpressionPrefix() {
            return "${";
        }

        @Override
        public String getExpressionSuffix() {
            return "}";
        }
    };
}
